package com.molyfun.parents.activity.msg;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.ask.view.MultChooseBarView;
import com.molyfun.parents.activity.msg.adapter.MsgListAdapter;
import com.molyfun.parents.fragment.BaseFragment;
import com.molyfun.parents.push.PushMsgCacheCenter;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.MsgDeleteBatRequest;
import com.molyfun.parents.rest.bean.MsgListResponse;
import com.molyfun.parents.rest.bean.UserResponse;
import com.molyfun.parents.view.swipeRefreshLayout.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SystemMsgFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener, MultChooseBarView.MultChooseCallback, MsgListAdapter.MsgListAdapterCallback, View.OnClickListener {

    @InjectView(R.id.msg_list)
    RecyclerView mRecyclerView;
    @InjectView(R.id.empty_layout)
    LinearLayout mEmptyLayout;
    @InjectView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @InjectView(R.id.mult_choose_bar)
    MultChooseBarView mMultChooseBarView;

    private LinearLayoutManager mLayoutManager;
    private MsgListAdapter mMsgListAdapter;
    private String TAG = "MineMsgActivity";
    private int mCurrentPage = RestClient.DEFAULT_PAGE;
    private boolean mHasMoreData = true;
    private Handler mHandler = new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_system_msg, container, false);
        ButterKnife.inject(this, view);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setOnLoadListener(this);
        mSwipeRefreshLayout.setTopColor(R.color.refresh_color_01, R.color.refresh_color_02,
                R.color.refresh_color_02, R.color.refresh_color_01);
        mSwipeRefreshLayout.setBottomColor(R.color.color_transparent, R.color.color_transparent,
                R.color.color_transparent, R.color.color_transparent);
        mSwipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeRefreshLayout.setLoadNoFull(true);

        mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mMsgListAdapter = new MsgListAdapter(getContext());
        mRecyclerView.setAdapter(mMsgListAdapter);
        mMultChooseBarView.setMultChooseCallback(this);
        System.out.println(TAG + "onCreateView()");
        loadData(true);
        mMsgListAdapter.setMsgListAdapterCallback(this);

        return view;
    }

    @Override
    public void onRefresh() {
        if (mOnMsgTabMainCallback != null) {
            mOnMsgTabMainCallback.onMultChooseBarOperationClick();
        }

        if(lastTimeInt == 0l){
            loadData(true);
            lastTimeInt = System.currentTimeMillis();
        }else{
            long nowTime = System.currentTimeMillis();
            if(nowTime - lastTimeInt > 500){
                loadData(true);
                lastTimeInt = nowTime;
            }
        }
        System.out.println(TAG + "onRefresh()");
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
    }

    @Override
    public void onEditBegin() {
        mMsgListAdapter.beginChooseEditMode();
        mRecyclerView.scrollToPosition(mMsgListAdapter.getItemCount() - 1);
    }

    @Override
    public void onClick(View v) {

    }

    private long lastTimeInt = 0l;

    @Override
    public void onLoad() {
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
        if (mHasMoreData) {
            mCurrentPage++;
            System.out.println(TAG + "onLoad()");
            loadData(false);
        }
    }

    private void loadData(final boolean isRefresh) {
//        topicAdapter.notifyDataSetChanged();
        if (isRefresh) {
            mCurrentPage = RestClient.DEFAULT_PAGE;
        }
        System.out.println(TAG + "loadData()");
        showProgressDialog();

        Call<MsgListResponse> call = MFPApplication.getInstance().getRestClient().getMsgList(mCurrentPage, RestClient.DEFAULT_PAGE_SIZE);
        call.enqueue(new Callback<MsgListResponse>() {
            @Override
            public void onResponse(Call<MsgListResponse> call, Response<MsgListResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getData() != null && response.body().getData().getRecords() != null) {
                    if (response.body().getCode() == 200) {
                        System.out.println("++------->成功回调");
                        if (isRefresh) {
                            if (response.body().getData().getRecords().size() > 0) {
                                mMsgListAdapter.refreshData(response.body().getData().getRecords());
                                mHasMoreData = true;
                                mEmptyLayout.setVisibility(View.GONE);
                            } else {
                                mHasMoreData = false;
                                mEmptyLayout.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (response.body().getData().getRecords().size() > 0) {
                                mHasMoreData = true;
                            } else {
                                mHasMoreData = false;
                            }
                            mMsgListAdapter.addAll(response.body().getData().getRecords());
                        }
                    } else {
                        toast(response.body().getMsg());
                        if (isRefresh) {
                            mMsgListAdapter.clearAll();
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        }
                    }

                } else {
                    System.out.println("++------->无数据回调");
                    if (response.body() != null) {
                        toast(response.body().getMsg());
                    }
                    if (isRefresh) {
                        mMsgListAdapter.clearAll();
                        mEmptyLayout.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onFailure(Call<MsgListResponse> call, Throwable t) {
                System.out.println("++------->失败回调");
                mMsgListAdapter.clearAll();
                mEmptyLayout.setVisibility(View.VISIBLE);
                dismissProgressDialog();
            }
        });

        if (isRefresh) {
            getUserInfo();
        }

    }

    //为了获取未读消息数
    private void getUserInfo() {
        Call<UserResponse> call = MFPApplication.getInstance().getRestClient().getUserInfo();
        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                if (response.body() != null && response.body().getData() != null) {
                    PushMsgCacheCenter.getInstance().setmCurrentUnreadCount(response.body().getData().getMessageunreadcount());
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {

            }
        });
    }

    @Override
    public void onAllChoose() {
        //全选的逻辑
        mMsgListAdapter.checkAllMsg();
    }

    private void delMsgList(HashSet<MsgListResponse.MsgBean> msgBeen) {
        if (msgBeen == null || msgBeen.size() == 0){
            toast("请先选择");
            return;
        }
        showProgressDialog();
        MsgDeleteBatRequest msgDeleteBatRequest = new MsgDeleteBatRequest();
        List<MsgDeleteBatRequest.MsgIdBean> msgIdBeanList = new ArrayList<>();
        for (MsgListResponse.MsgBean msgBean : msgBeen) {
            MsgDeleteBatRequest.MsgIdBean msgIdBean = new MsgDeleteBatRequest.MsgIdBean(msgBean.getId());
            msgIdBeanList.add(msgIdBean);
        }
        msgDeleteBatRequest.setIdlist(msgIdBeanList);

        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().batDelMsg(msgDeleteBatRequest);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                if (response.body() != null) {
                    mMsgListAdapter.deleteCheckMsg();
                    if(mMultChooseBarView != null){
                        mMultChooseBarView.reset();
                    }
                    mMsgListAdapter.endChooseEditMode();

                    if (mOnMsgTabMainCallback != null) {
                        System.out.println("MainTabMsgFragment" + "删除成功");
                        mOnMsgTabMainCallback.onMultChooseBarOperationClick();
                    }
                    toast("删除成功");
                    dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {

            }
        });
    }

    @Override
    public void onCancel() {
        //取消全选的逻辑
        mMsgListAdapter.uncheckAllMsg();
        mMsgListAdapter.endChooseEditMode();
        mMultChooseBarView.reset();
    }

    @Override
    public void onOperationClick() {
        //删除的操作
        delMsgList(mMsgListAdapter.getmChoosedList());
    }

    public void setMsgDateChangeListener(OnMsgTabMainCallback onMsgTabDateChangeListener) {
        this.mOnMsgTabMainCallback = onMsgTabDateChangeListener;
    }

    private OnMsgTabMainCallback mOnMsgTabMainCallback;

    @Override
    public void setMsgId(String msgId) {
        setMsgViewed(msgId);
    }


    public interface OnMsgTabMainCallback {

        void onMultChooseBarOperationClick();
    }

    private void setMsgViewed(String msgId) {
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().readMsg(msgId);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

}
